#include "StdAfx.h"
#include "Sky.h"
#include "TextureMgr.h"
#include <string>



void Sky::init(ID3D10Device *device, float radius)
{
	this->mD3dDevice = device;
	this->mCubeMap = GetTextureMgr().createTex( L"uffizi_cross.dds" );

	this->mTech			= fx::SkyFX->GetTechniqueByName("SkyTech");
	this->mfxWVPVar		= fx::SkyFX->GetVariableByName("gWVP")->AsMatrix();
	this->mfxCubeMapVar = fx::SkyFX->GetVariableByName("gCubeMap")->AsShaderResource();

	this->buildBuffers(radius);
}

void Sky::update(float dt)
{
}

void Sky::draw()
{
	D3DXVECTOR3 eyePos = GetCamera().position();

	D3DXMATRIX world;
	D3DXMatrixTranslation(&world, eyePos.x, eyePos.y, eyePos.z);
	D3DXMATRIX view = GetCamera().view();
	D3DXMATRIX proj = GetCamera().proj();
	D3DXMATRIX WVP  = world * view * proj;

	HR( this->mfxWVPVar->SetMatrix((float*) WVP) );
	HR( this->mfxCubeMapVar->SetResource(this->mCubeMap) );

	UINT stride = sizeof(SkyVertex);
	UINT offset = 0;
	this->mD3dDevice->IASetVertexBuffers(0, 1, &this->mVertexBuffer, &stride, &offset);
	this->mD3dDevice->IASetIndexBuffer(this->mIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
	this->mD3dDevice->IASetInputLayout(InputLayout::Pos);
	this->mD3dDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	D3D10_TECHNIQUE_DESC techDesc;
	this->mTech->GetDesc(&techDesc);
	for (UINT p = 0; p < techDesc.Passes; ++p) {
		ID3D10EffectPass *pass = this->mTech->GetPassByIndex(p);
		pass->Apply(0);
		this->mD3dDevice->DrawIndexed(this->mNumIndices, 0, 0);
	}
	/*
	*/
}

void Sky::buildBuffers(float radius)
{
	std::vector<D3DXVECTOR3> vertices;
	std::vector<DWORD> indices;

	BuildGeoSphere(2, radius, vertices, indices);

	std::vector<SkyVertex> skyVertices(vertices.size());
	for (size_t i = 0; i < vertices.size(); ++i) {
		skyVertices[i].pos = vertices[i];
		skyVertices[i].pos.y *= 0.5f;
	}

	D3D10_BUFFER_DESC vbd;
	ZeroMemory( &vbd, sizeof(vbd) );
	vbd.Usage = D3D10_USAGE_IMMUTABLE;
	vbd.ByteWidth = sizeof(SkyVertex) * (UINT) skyVertices.size();
	vbd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
	
	D3D10_SUBRESOURCE_DATA vInitData;
	vInitData.pSysMem = &skyVertices[0];
	HR( this->mD3dDevice->CreateBuffer(&vbd, &vInitData, &mVertexBuffer) );

	this->mNumIndices = indices.size();

	D3D10_BUFFER_DESC ibd;
	ZeroMemory( &ibd, sizeof(ibd) );
	ibd.Usage = D3D10_USAGE_IMMUTABLE;
	ibd.ByteWidth = sizeof(DWORD) * indices.size();
	ibd.BindFlags = D3D10_BIND_INDEX_BUFFER;

	D3D10_SUBRESOURCE_DATA iInitData;
	iInitData.pSysMem = &indices[0];
	HR( this->mD3dDevice->CreateBuffer(&ibd, &iInitData, &mIndexBuffer) );
}
